/*
 ********************************************************************************
 *
 * Copyright (c) 2020-2024 Renesas Electronics Corporation and/or its affiliates
 *
 ********************************************************************************
 */

package com.dialog.suotalib.utils;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

public class SuotaUtil {

    private static final String HEX_DIGITS_LC = "0123456789abcdef";
    private static final String HEX_DIGITS_UC = "0123456789ABCDEF";

    public static String hexArray(byte[] v, boolean uppercase, boolean brackets) {
        if (v == null)
            return "[]";
        String hexDigits = uppercase ? HEX_DIGITS_UC : HEX_DIGITS_LC;
        StringBuilder buffer = new StringBuilder(v.length * 3 + 3);
        if (brackets)
            buffer.append("[ ");
        for (byte b : v) {
            buffer.append(hexDigits.charAt((b >> 4) & 0x0f)).append(hexDigits.charAt(b & 0x0f)).append(" ");
        }
        if (brackets)
            buffer.append("]");
        else if (buffer.length() > 0)
            buffer.setLength(buffer.length() - 1);
        return buffer.toString();
    }

    public static String hexArray(byte[] v) {
        return hexArray(v, false, true);
    }

    public static String getName(BluetoothDevice device) {
        try {
            return device.getName();
        } catch (SecurityException e) {
            return null;
        }
    }

    public static boolean checkConnectPermission(Context context) {
        return Build.VERSION.SDK_INT < 31 || context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED;
    }
}
